package com.adam.masterSpringMVC4.weibo;

import com.adam.masterSpringMVC4.controller.WeiboController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WeiboService {

    private List<WeiboData> weiboDataList = new LinkedList<>();
    @Autowired
    private WeiboCache weiboCache;

    @PostConstruct
    public void extractWeibos() {
        try (InputStream inputStream = WeiboService.class.getResourceAsStream("/weibo-data.txt");
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))
        ) {
            char[] buffer = new char[10240];
            int len = reader.read(buffer);
            int ln = 0;
            for(int i=0;i<len;i++) {
                char c = buffer[i];
                if(c == '\n') {
                    String lineStr = new String(buffer, ln, i-ln);
                    ln = i+1;
                    String[] tokens = lineStr.split("\t");
                    weiboDataList.add(new WeiboData(tokens[2], tokens[0], tokens[3], tokens[1]));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<WeiboData> search(String keyword) {
        return weiboDataList
                .stream()
                .filter(weiboData -> weiboData.getWeibo().contains(keyword))
                .collect(Collectors.toList());
    }

    public List<WeiboData> search(String searchType, List<String> keywords) {
        return keywords.stream()
                .flatMap(keyword -> weiboCache.fetch(searchType, keyword).stream())
                .collect(Collectors.toList());
    }

}
